package com.hzl.lease.common.utils;

import com.hzl.lease.common.exception.LeaseException;
import com.hzl.lease.common.result.ResultCodeEnum;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.util.Date;

public class JwtUtil {
    private static final Long expire=1000 * 60 * 60l;   // 1000ms * 60s * 60min = 24h
    private static  SecretKey secretKey = Keys.hmacShaKeyFor("b8ad08a3a547e35829b821b75370301dd8c4b06bdd7771f9b541a75914068718".getBytes());//签名
    /*
     *    创建token
     * token: 包含三部分: 头,负载,签名
     *   负载: 在token中保存的登录用户的相关信息(userName账号,userId唯一标识)
     * eyJhbGciOiJIUzUxMiIsInppcCI6IkdaSVAifQ.
     * H4sIAAAAAAAA_6tWKi5NUrJSyslPz8zTLcnPTs1T0lFKrShQsjI0N7Y0MjE1NLDUUSotTi3yTAGKQZh-ibmpQE2JKbmZeUq1AFZ7_ANEAAAA.
     * yYwCUzNm3C4UvjFIFRbsxorSeqMRlZLiJSRrKV8aCvgO60EblzBL7Jbiokfw_gFXgAXo0gNbFvMC66ir0S16VQ
     * */
    public static  String createToken(String userName,Long userId){

        String token = Jwts.builder()
                .setSubject("login-token") //token中的主题
                .setExpiration(new Date(System.currentTimeMillis() + expire)) //token的过期时间
                .claim("userId", userId)    //登录用户的唯一表示id
                .claim("userName", userName)  //登录用户的账号
                .signWith(secretKey) //签名
                .compressWith(CompressionCodecs.GZIP) //对token进行压缩: 建设带宽的占用
                .compact();  //创建token

        return token;
    }

    //解析token

    public static Claims parseToken(String token){
        Jws<Claims> claimsJws = null;
        try {
            claimsJws = Jwts.parserBuilder().setSigningKey(secretKey).build().parseClaimsJws(token);
        } catch (ExpiredJwtException e) {
            throw new LeaseException(ResultCodeEnum.TOKEN_EXPIRED);
        }catch (JwtException e){
            throw new LeaseException(ResultCodeEnum.TOKEN_INVALID);
        }
        return claimsJws.getBody();
    }


    //测试生成token
    public static void main(String[] args) {
        String token = createToken("admin",1l);
        System.out.println("token = " + token);
                        //解析刚刚生成的token
        Claims claims = parseToken(token);
        System.out.println("claims = " + claims);
    }
}
